
<html> 
 <head> 
  <title> Binder : Setup </title> 
  <LINK HREF="setup.css" TYPE="text/css" REL="stylesheet">
 </head>
<body> 
<?php
/**
* Binder Setup
*
* $Id: setup.php 38 2005-04-03 06:02:47Z vluther $ 				
* @package user_interface
* @version $Rev: 38 $
* @copyright Copyright &copy; 2000-2007, Linuxpowered, Inc               
* @author Vidyut Luther <vid@linuxpowered.com> 
**/
  error_reporting(E_ALL);

  function make_mysql_perms()
  {
    global $_POST; 
    $hostname = trim($_POST['mysql_hostname']);
    $user = trim($_POST['mysql_username']);
    $pass = trim($_POST['mysql_userpass']);
    $db = trim($_POST['mysql_dbname']);
    $rootuser = trim($_POST['mysql_root']); 
    $rootpass = trim($_POST['mysql_rootpass']);
   
   
    $link = @mysql_connect("$hostname","$rootuser","$rootpass") ; 
    if(!$link) {
      echo "<span class='form_title'> Could not connect as Root User, Please make sure you gave the right password </span> <br> ";
      die; 
      return false; 
    } 
    // Now give the user permission.
		
    $sql2 = "CREATE database IF NOT EXISTS $db "; 
    mysql_query($sql2); 
    $sql = "GRANT ALL ON $db.* TO $user@'localhost' IDENTIFIED BY '$pass'";
    $rs = mysql_query($sql) ; 
    return true;  
  }

  /**
   * Check the mysql username/password provided by the form, make sure the username/password have access to 
   * the database, and that the database exists, if it doesn't try to create it.
   *
   * @param string $user
   * @param string $pass
   * @param string $hostname
   * @param string $db
   *
   * @return string
   */
  function check_mysql_perms($user,$pass,$hostname,$db)
  {
  	global $_POST; 
  	$rootuser = trim($_POST['mysql_root']); 
    $rootpass = trim($_POST['mysql_rootpass']);
    echo "Checking Hostname ... $hostname <br>";
    echo "Checking Username ... $user <br>";
    echo "Checking Password .... $pass <br>"; 
    $link = @mysql_connect("$hostname","$user","$pass") ; 
    
    if(!$link) {
      echo "<font color='red'>Could not connect to the DB Server ($hostname). Trying as the root user.</font> <br>";
      $rlink = @mysql_Connect($hostname,$rootuser,$rootpass); 
      if(!$rlink) { 
      	echo "<font color='red'> The Root user could not connect. Fatal Error. Please make sure you entered everything properly </font> <br>"; 
      	die; 
      } else { 
      	echo "Able to connect as the Root user. Going to add $user to the Database, and create $db if need be <br>";
      	if(!make_mysql_perms()) {
      		die;
        	return false; 
      	}
      	
      }
    } else {
      echo "Connected to MySQL ... <br>"; 
    }

    // Now try to select the db.  
    $dblink = mysql_select_db($db,$link);
    if(!$dblink) {
      echo "Could not connect to the database , trying to figure out what to do .... <br>"; 
      $sql = "CREATE database IF NOT EXISTS $db"; 
      $rs = mysql_query($sql);
      if(!$rs) {
        echo "The user specified could not create the database, Make sure the user has proper permissions</span> <br>"; 
        return false ; 
      } else {
        echo "The Database named  '$db'  created.<br> "; 
      } 
    } else {
      echo "Database Selected </span> <br>"; 
    }
 		return true;
  }


  /**
   * Create the tables for the specific database.
   *
   * @param string $user
   * @param string $pass
   * @param string $hostname
   * @param string $db
   * 
   * @return string
   */
  function build_mysql($user,$pass,$hostname,$db) 
  {
  	// this assumes the check_mysql_perms passed. 
  	$contents = implode("", file("sql/binder.sql")); 
    $queries = explode(";", $contents);
    unset($queries[count($queries)-1]);
		$link = mysql_connect("$hostname","$user","$pass") ;
		$dblink = mysql_select_db($db,$link);
		
    foreach($queries as $query) {
			if(!mysql_query($query,$link)) {
				echo "<font color='red'> Problem with $query ... " . mysql_error() . "</font> <BR>";
				die; 
			} 
		}  	
		
		return true; 
	}

	/**
	 * Creates the Default Admin User. 
	 *
	 * @param string $user
	 * @param string $pass
	 * @param string $hostname
	 * @param string $db
	 * @param string $wuser
	 * @param string $wpass
	 */
	function create_user($user,$pass,$hostname,$db,$wuser,$wpass)
	{
		$link = mysql_connect("$hostname","$user","$pass") ;
		$dblink = mysql_select_db($db,$link);
		
		$sql = "INSERT INTO `users` (`userid`, `password`, `firstname`, `lastname`, `email`, `level`) VALUES (1, '$wpass', 'Admin', 'User', '$wuser', 0)"; 		
		if(!mysql_query($sql)) {
			echo "Problem Creating Admin User </span> " . mysql_error() . "<br> "; 
		} else {
			return true;
		} 
	}

	
if(empty($_POST)) {
  // Go and run the pre-checker first. If Things pass, then show the form. 
  
  $ready = preCheck(); 
  
  if($ready) {  
    $showform = true;
    echo "<p> Pre Requisites met, proceed with install </p> ";  
  } else { 
    echo "<a href='setup.php'> Click Here to Reload </a> ";
  }
  

  
  $mysql_hostname = "localhost";
  $mysql_username = "binder"; 
  $mysql_username = '';
  $mysql_userpass = '';
  $mysql_dbname = '';
  $mysql_rootuser = ''; 
  $mysql_rootpass = '';     
  
  $soa_ttl = '5M'; 
  $default_serial = date("YmdH");  
  $default_refresh = '5m'; 
  $default_cache = '1D'; 
  $default_expire = '30D'; 
  $default_retry = '15M'; 
  $soa_mname = ''; 
  $soa_rname = ''; 
  $pdns = ''; 
  $sdns = ''; 
  $tdns = ''; 
  $company_name = ''; 
  $support_email = '';  
   
  $web_hostname = $_SERVER['SERVER_NAME']; 
  $web_relpath = str_replace('setup.php','',$_SERVER['REQUEST_URI']);
  $web_username = ''; 
  $web_userpass = ''; 
  $web_servpath = str_replace('setup.php','',$_SERVER['SCRIPT_FILENAME']);
 
} else { 

  $mysql_hostname = trim($_POST['mysql_hostname']);
  $mysql_username = trim($_POST['mysql_username']); 
  $mysql_userpass = trim($_POST['mysql_userpass']);
  $mysql_dbname = trim($_POST['mysql_dbname']); 
  $mysql_rootuser = trim($_POST['mysql_root']);  
  $mysql_rootpass = trim($_POST['mysql_rootpass']); 
  $createdb = @trim($_POST['create_db']);
  $web_hostname = trim($_POST['web_hostname']); 
  $web_username = trim($_POST['web_username']); 
  $web_userpass = trim($_POST['web_userpass']); 
  $web_relpath = trim($_POST['web_relpath']); 
  $web_servpath = trim($_POST['web_servpath']) ;  
  
  
  $soa_mname = trim($_POST['soa_mname']); 
  $soa_rname = trim($_POST['soa_rname']);
  $default_serial = trim($_POST['soa_serial']);  
  $default_refresh = trim($_POST['soa_refresh']); 
  $default_retry = trim($_POST['soa_retry']); 
  $default_expire = trim($_POST['soa_expire']); 
  $default_cache = trim($_POST['soa_cache']);
  $pdns = trim($_POST['primary_dns']); 
  $sdns = trim($_POST['secondary_dns']); 
  $tdns = trim($_POST['tertiary_dns']);  

  $company_name = trim($_POST['company_name']); 
  $support_email = trim($_POST['support_email']); 
?>
<div id="setupForm"><div class="title"><span class="form_title">Binder Setup </span> </div>
<?php
	if($createdb == "yes") {
		echo "Creating the Database .. "; 
		make_mysql_perms(); 
	}
  $mysqlcheck = check_mysql_perms($mysql_username,$mysql_userpass,$mysql_hostname,$mysql_dbname) ;  
  if($mysqlcheck) {
  	echo "MySQL Permissions Succeeded, Populating the tables </span> <br> "; 
 		if(build_mysql($mysql_username,$mysql_userpass,$mysql_hostname,$mysql_dbname)) {
 			echo "Database Created, Creating Admin User for default login </span> <br> "; 
 			create_user($mysql_username,$mysql_userpass,$mysql_hostname,$mysql_dbname,$web_username,$web_userpass); 
 			// If this passed, set the configuration settings.
 			set_configuration($_POST);
 		}
 	}
 	
 	echo "<p> Binder Setup is Complete. <br>Please remove the setup.php file, and go to <br> <a href='http://$web_hostname/$web_relpath'> Your Binder Install </a>  <br> "; 

}

if(isset($showform)) {
?>

&nbsp; *<span class="req">Required Information</span> 
<form action="setup.php" method="POST"> 
<div id="setupForm"><div class="title"><span class="form_title">Organisation Information </span> </div>
    Company Name
      <input name="company_name" class="req" size="60" maxsize="60" value="<?php echo $company_name; ?> " type="text" />
    Support Email 
      <input name="support_email" class="req" size="60" maxsize="60" value="<?php echo $support_email;?> " type="text" />
       <div class="pad"> </div> 
</div>



<div id="setupForm"><div class="title"><span class="form_title">MySQL Information </span> </div>
    MySQL Server Hostname 
      <input name="mysql_hostname" class="req" size="60" maxsize="60" value="<?php echo $mysql_hostname; ?> " type="text" />
    MySQL User Name 
      <input name="mysql_username" class="req" size="60" maxsize="60" value="<?php echo $mysql_username;?> " type="text" />
    MySQL User Password 
      <input name="mysql_userpass" class="req" size="60" maxsize="60" value="<?php echo $mysql_userpass; ?>" type="text" />
    MySQL Database Name 
      <input name="mysql_dbname" class="req" size="60" maxsize="60" value="<?php echo $mysql_dbname; ?>" type="text" />
     MySQL Root User Name (If the user above does not already exist, or have sufficient privileges) 
      <input name="mysql_root" size="60" maxsize="60" value="<?php echo $mysql_rootuser; ?>" type="text" />
    MySQL Root User Password 
      <input name="mysql_rootpass" size="60" maxsize="60" value="<?php echo $mysql_rootpass; ?>" type="text" />
    <div class="pad"> </div> 
</div>

<div id="setupForm"><div class="title"><span class="form_title">Webserver Information </span>  &nbsp;  </div>

    Web Server Hostname 
      <input name="web_hostname" class="req" size="60" maxsize="60" value="<?php echo $web_hostname; ?>" type="text" />
    Web Server Relative Path 
      <input name="web_relpath" class="req" size="60" maxsize="60" value="<?php echo $web_relpath; ?>" type="text" />
    Path to Files on the Server
      <input name="web_servpath" class="req" size="60" maxsize="60" value="<?php echo $web_servpath; ?>" type="text" />
    Default Admin Username (you can add more later)
      <input name="web_username" class="req" size="60" maxsize="60" value="<?php echo $web_username; ?>" type="text" />
    Default Admin Password (can be changed later)
      <input name="web_userpass" class="req" size="60" maxsize="60" value="<?php echo $web_userpass; ?>" type="text" />
    <div class="pad"> </div> 
    
</div>

<div id="setupForm"><div class="title"><span class="form_title">Default Domain SOA Information </span>  <strong> Do Not Change the Defaults, unless you are 100% sure </strong>   </div>

    Default TTL (Time to Live) <strong> ** In Minutes ** </strong> 
      <input name="soa_ttl" class="req" size="3" maxsize="3" value="<?php echo $soa_ttl; ?> " type="text" />
    Default MNAME (Specify the domain name of the zone's primary master name server)  
      <input name="soa_mname" class="req" size="60" maxsize="60" value="<?php echo $soa_mname;  ?>" type="text" />
    Default RNAME (Email Address of Zone Admin)
      <input name="soa_rname" class="req" size="60" maxsize="60" value="<?php echo $soa_rname; ?>" type="text" />
    Serial Number (computed automatically, you do not need to change this manually 99% of the time)
    <input name="soa_serial" class="req" size="12" maxsize="11" READONLY value="<?php echo $default_serial; ?> " type="text" />
    Default REFRESH Rate
      <input name="soa_refresh" class="req" size="5" maxsize="5" value="<?php echo $default_refresh; ?> " type="text" />
    Default RETRY Rate
      <input name="soa_retry" class="req" size="5" maxsize="5" value="<?php echo $default_retry;?>" type="text" />
    Default EXPIRE Rate
      <input name="soa_expire" class="req" size="5" maxsize="5" value="<?php echo $default_expire;?>" type="text" />
    Default Negative Cache Rate
      <input name="soa_cache" class="req" size="5" maxsize="5" value="<?php echo $default_cache;?>" type="text" />
    Default Primary Name Server 
      <input name="primary_dns" class="req" size="60" maxsize="60" value="<?php echo $pdns; ?> " type="text" />
    Default Secondary Name Server
      <input name="secondary_dns" class="req" size="60" maxsize="60" value="<?php echo $sdns; ?> " type="text" />
    Default Tertiary Name Server
      <input name="tertiary_dns" size="60" maxsize="60" value="<?php echo $tdns; ?> " type="text" />
      
    <div class="pad"> </div> 
   
    <input type="submit" class="loginButton" value="Configure Binder " />  &middot; <input type="reset" class="loginButton" value="Reset">
</div>

</form> 

</body> 
</html> 

<?php

}
	/**
	 * Sets the Configuration settings in the Database. 
	 *
	 * @param array $_POST
	 */
	function set_configuration($_POST)
	{
		$hostname = trim($_POST['mysql_hostname']);
  	$user = trim($_POST['mysql_username']); 
  	$pass = trim($_POST['mysql_userpass']);
  	$db = trim($_POST['mysql_dbname']);
    $path = trim($_POST['web_servpath']); 
    $company_name = trim($_POST['company_name']); 
    $support_email = trim($_POST['support_email']); 
    $web_hostname = trim($_POST['web_hostname']); 
  	$web_username = trim($_POST['web_username']); 
  	$web_userpass = trim($_POST['web_userpass']); 
  	$web_relpath = trim($_POST['web_relpath']); 
  	$web_servpath = trim($_POST['web_servpath']) ;  
  
  
 
  	$company_name = trim($_POST['company_name']); 
  	$support_email = trim($_POST['support_email']); 
    	
  	$link = mysql_connect("$hostname","$user","$pass") ;
		$dblink = mysql_select_db($db,$link);
		unset($_POST['createdb']); 
		$fields = ''; 
		$values = ''; 
		$sql = "INSERT INTO binder_config ("; 
  	foreach($_POST as $key=>$value) {
  		if(!eregi('mysql',$key)) {
 	  		echo "Setting <strong> $key </strong> => $value <br> "; 
  			$fields .= "$key,"; 
  			$values .= "'$value',";
  		}
  	}
		$fields = substr($fields,0,-1) ;
		$fields .= ") VALUES (";  
		$values = substr($values,0,-1); 
  	$fullsql = $sql . $fields . $values . ")"; 
  	mysql_query($fullsql); 
  
  	// Now Create the config.inc.php 
  	#$config_contents = implode("\n",file("config.inc.php")); 
    $configfile = $path . "/config.inc.php.template"; 
    echo "Opening .. $configfile "; 
    $config_contents = file_get_contents($configfile); 
   
    $config_contents = str_replace("%{MYUSER}%", $user, $config_contents);
    $config_contents = str_replace("%{MYPASS}%", $pass, $config_contents);
    $config_contents = str_replace("%{MYHOST}%", $hostname, $config_contents);
    $config_contents = str_replace("%{MYDB}%", $db, $config_contents);
  	$config_contents = str_replace("%{INCLUDEPATH}%", $path."includes/", $config_contents);
  
    #echo "Configuration Contents .. $config_contents"; 
    $fp = fopen($path.'/config.inc.php','w') ; 
    if ($fp === FALSE) {
        return "Could not open the file 'config.inc.php' for writing. The permissions on the file should be set as to allow the user that the web server runs as to open it. Please correct this problem and try again.";
    }
    $res = fwrite($fp, $config_contents);
    if ($fp === FALSE) {
        return "Could not write the configuration information to 'config.inc.php'. The file should be writable by the user that the web server runs as. Please correct this problem and try again.";
    }       
    fclose($fp);	
  	
  		
	}



/**
 * preCheck: Check permissions etc before starting installer. 
 * 
 * @return 
 * @access 
 **/
  function preCheck()
  {
    /* 
      Things to Check: 
        templates_c must be writeable 
        logs , must be writeable 
        php version should be 4.3.10 or higher.
    */
  
  $return = ""; 

  #Version of PHP Greater than 4.3 ?

  if(version_compare(phpversion(),'4.3','<')) {
    $phpvimg = "stop.gif"; 
    $return = "bad"; 
  } else {
    $phpvimg = "ok.png"; 
  }

  #Do we have MySQL Support ? 

  if(function_exists('mysql_connect')) {
    $phpmyimg = "ok.png"; 
  } else {
    $phpmyimg = "stop.gif";
    $return = "bad";  
  }

  # Templates_c 
  if(!is_writable('templates_c')) { 
     $tplimg = "stop.gif";
     $return = "bad";  
  } else {
     $tplimg = "ok.png"; 
  }


  #Logs 
  if(!is_writable('logs')) { 
    $logimg = "stop.gif";
    $return = "bad";  
  } else {
    $logimg = "ok.png"; 
  }
  
  #Config.inc.php 
  if(!is_writable('config.inc.php')) { 
    $return = "bad"; 
    $cfimg = "stop.gif"; 
  } else {
    $cfimg = "ok.png"; 
  }

  $web_servpath = str_replace('setup.php','',$_SERVER['SCRIPT_FILENAME']);

   
?>

<div id="setupForm"><div class="title"><span class="form_title"> Installation Precheck </span> </div>
Just checking some pre-requisites first. If any of the items here are flagged as not ok, please take the 
necessary steps to make sure they meet the requirements. For now, the setup screen will not let
you proceed until all requirements are met.  

<table> 

<p>
PHP Version (<?php echo phpversion(); ?>) > 4.3.x ?  <img src="images/<?php echo $phpvimg; ?>" height="16" width="16">  
MySQL Support (<?php echo @mysql_get_server_info(); ?>) <img src="images/<?php echo $phpmyimg; ?>" height="16" width="16"> 
<?php echo $web_servpath; ?>config.inc.php is writeable ?  <img src="images/<?php echo $cfimg;?>" height="16" width="16">   
<?php echo $web_servpath; ?>templates_c is writeable ? <img src="images/<?php echo $tplimg;?>" height="16" width="16">  
<?php echo $web_servpath; ?>logs  <img src="images/<?php echo $logimg;?>" height="16" width="16">  </p> 


</div> 
<?php

    if($return == "bad") {
      return false; 
    } else {
      return true; 
    }
 
  }

?>
